import os
import time
import asyncio
from pathlib import Path
from .constants import UPLOAD_DIR, CUT_DIR

async def cleanup_temp_files():
    """清理24小时前的临时文件"""
    while True:
        try:
            current_time = time.time()
            # 清理上传目录
            for file in UPLOAD_DIR.glob("*"):
                if file.stat().st_mtime < current_time - 86400:  # 24小时 = 86400秒
                    try:
                        file.unlink()
                    except:
                        pass
            
            # 清理裁剪目录
            for file in CUT_DIR.glob("*"):
                if file.stat().st_mtime < current_time - 86400:
                    try:
                        file.unlink()
                    except:
                        pass
        except Exception as e:
            print(f"清理临时文件失败: {str(e)}")
        
        # 每小时检查一次
        await asyncio.sleep(3600)

async def cleanup_batch_cut_files(video_id: str):
    """清理批量裁剪的上传文件"""
    try:
        # 删除所有以 video_id_ 开头的上传文件
        deleted = 0
        for file in UPLOAD_DIR.glob(f"{video_id}_*"):
            try:
                file.unlink()
                deleted += 1
            except Exception as e:
                pass
        return {"status": "success", "deleted": deleted}
    except Exception as e:
        return {"error": f"清理失败: {str(e)}"} 